package controllers

import (
	"errors"
	"github.com/gin-gonic/gin"
	form2 "meituan/apps/mine/form"
	"meituan/apps/mine/models"
	db2 "meituan/db"
	"meituan/utils/page"
	"meituan/utils/password"
	"meituan/utils/response"
	"strconv"
)

// QueryUser 查询用户
func QueryUser(ctx *gin.Context) {
	form := form2.NewQueryUserForm()
	e := ctx.ShouldBindQuery(form)
	if e != nil {
		response.SendError(ctx, e, 400)
		return
	}

	db, _ := db2.NewDB()
	defer db.Close()
	result := make([]models.User, 10)
	query := db.Model(&models.User{}).
		Where("username like concat(\"%\",?,\"%\")", form.Username).
		Where("province like concat(\"%\",?,\"%\")", form.Province).
		Where("city like concat(\"%\",?,\"%\")", form.City).
		Where("area like concat(\"%\",?,\"%\")", form.Area).Omit("password")
	if form.Status != 0 {
		query = query.Where("status = ?", form.Status)
	}
	if form.UserType != 0 {
		query = query.Where("user_type = ?", form.UserType)
	}
	total, current, _ := page.Pagination(query, ctx.DefaultQuery("current", "1"), &result)

	ctx.JSON(200, gin.H{
		"code": 200,
		"data": result,
		"page": map[string]interface{}{
			"current": current,
			"total":   total,
		},
	})
}

// DeleteUser 删除用户
func DeleteUser(ctx *gin.Context) {
	id := ctx.Param("id")
	if num, e := strconv.Atoi(id); e != nil {
		response.SendError(ctx, errors.New("未找到对象"), 404)
	} else {
		db, _ := db2.NewDB()
		defer db.Close()
		user := &models.User{}
		user.ID = uint(num)
		db.Model(user).Delete(user)
		ctx.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除成功",
		})
	}
}

// UpdateUser 修改用户
func UpdateUser(ctx *gin.Context) {
	id := ctx.Param("id")
	if num, e := strconv.Atoi(id); e != nil {
		response.SendError(ctx, errors.New("未找到对象"), 404)
	} else {
		db, _ := db2.NewDB()
		defer db.Close()
		user := &models.User{}
		user.ID = uint(num)
		if e := ctx.ShouldBindJSON(user); e != nil {
			ctx.JSON(400, gin.H{
				"code": 400,
				"msg":  e.Error(),
			})
			return
		}
		db.Model(user).Omit("password", "username").Update(user)
		if user.Password != "" {
			user.Password = password.Marshal(user.Password)
			db.Model(user).Select("password").Update(user)
		}
		ctx.JSON(200, gin.H{
			"code": 200,
			"msg":  user,
		})
	}
}

// CreateUser 新建用户
func CreateUser(ctx *gin.Context) {

	db, _ := db2.NewDB()
	defer db.Close()
	user := &models.User{}
	if e := ctx.ShouldBindJSON(user); e != nil {
		response.SendError(ctx, e, 400)
		return
	}
	user.Password = password.Marshal(user.Password)
	db.Model(user).Create(user)
	ctx.JSON(200, gin.H{
		"code": 200,
		"msg":  user,
	})

}

// UserInfo 用户详情
func UserInfo(ctx *gin.Context) {
	param := ctx.Param("id")
	result := new(models.User)
	db, _ := db2.NewDB()
	defer db.Close()
	db.Model(result).Where("id = ?", param).Find(result)
	ctx.JSON(200, gin.H{
		"code": 200,
		"data": result,
		"msg":  "获取成功",
	})
}
